<template name="add">
	<view class="add-main">
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="content">
				样品下单
			</block>
		</cu-custom>
		<scroll-view scroll-y class="add-scroll margin-bottom-xl padding-bottom-xl">
			<form>
				<view v-if="order.orderNumber" class="cu-form-group">
					<view class="title">订单编号</view>
					<view class="basis-regin text-right">
						<text>{{order.orderNumber}}</text>
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title">姓名</view>
					<input placeholder="请输入姓名" v-model="order.submitName" name="input" class="text-right"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">手机号</view>
					<input placeholder="请输入手机号" v-model="order.submitPhone" name="input" class="text-right"></input>
				</view>
				<view class="cu-form-group"   @tap="showDatePicker">
					<view class="title">送检日期</view>
					<view class="basis-regin text-right">
						<text>{{order.submitDate}}</text>
					</view>
					<text class='cuIcon-right'></text>
				</view>
				<view class="cu-form-group"  @tap="showRegionPicker">
					<view class="title">接收城市</view>
					<view class="basis-regin text-right">
						<text>{{order.acceptRegName}}</text>
					</view>
					<text class='cuIcon-right'></text>
				</view>
				<view class="cu-form-group" @tap="acceptUserShow">
					<view class="title">接收人</view>
					<view class="basis-regin text-right">
						<text>{{order.acceptUserName}}</text>
					</view>
					<text class='cuIcon-right'></text>
				</view>
				<view v-for="(item,index) in order.orderDetail" :key="index">
					<view class="bg-gray padding-bottom-sm"></view>
					<view class="cu-form-group" @click="simpleTypeShow(index)">
						<view class="title">样品种类</view>
						<view class="basis-regin text-right">
							<text>{{item.simpleTypeName}}</text>
						</view>
						<text class='cuIcon-right'></text>
					</view>
					<view class="cu-form-group" @click="normShow(index)">
						<view class="title">检测指标</view>
						<view class="basis-regin text-right">
							<text>{{item.norm+"("+item.amount+"元)"}}</text>
						</view>
						<text class='cuIcon-right'></text>
					</view>
					
					<view v-if="item.orderNumber" class="cu-form-group">
						<view class="title">样品编号</view>
						<view class="basis-regin text-right">
							<text>{{item.orderNumber}}</text>
						</view>
					</view>
					
					<view class="cu-form-group">
						<view class="title">原始编码</view>
						<input placeholder="请输入原始编码" v-model="item.originalCode" name="input" class="text-right"></input>
					</view>
				</view>
				<view class="flex justify-center margin-top margin-bottom-xl padding-bottom-xl">
					<text class="text-red" @click="simplePush">新增样品</text>
					<text class="text-red margin-left" @click="simpleRemove">删除样品</text>
				</view>
			</form>
		</scroll-view>
		<view class="cu-bar tabbar bg-white shadow foot">
			<view class="cu-bar btn-group flex">
				<view class="flex-sub flex flex-direction align-center justify-center">
					<view class="text-red text-price text-lg">{{actualAmount}}</view>
					<view class="text-red text-sm align-center">已优惠<span class="text-price">{{deductAmount}}</span></view>
				</view>
				<button class="flex-sub cu-btn text-green line-green shadow" @tap="addOrder(0)">存草稿</button>
				<button class="flex-sub cu-btn bg-green shadow-blur" @tap="addOrder(1)">下单</button>
			</view>
		</view>
		<w-picker mode="region"
			:defaultVal="['江苏省','南通市','如东县']"
			@confirm="regionChoose"
			ref="region" 
			:hideArea="false"
			themeColor="#f00">
		</w-picker>
		<w-picker
		    mode="date" 
		    startYear="2019" 
		    endYear="2099" 
		    :current="true" 
		    @confirm="dateChoose" 
		    ref="date" 
		    themeColor="#f00" 
		    >
		</w-picker>
		<w-picker v-if="simpleTypeList.length!=0" mode="selector" @confirm="simpleTypeChoose"
		 ref="simpleType" themeColor="#f00"
		 :selectList="simpleTypeList">
		</w-picker>
		
		<w-picker v-if="acceptUserList.length!=0" mode="selector" @confirm="acceptUserChoose"
		 ref="acceptUser" themeColor="#f00"
		 :selectList="acceptUserList">
		</w-picker>
		
		<w-picker v-if="normList.length!=0" mode="selector" @confirm="normChoose"
		 ref="norm" themeColor="#f00"
		 :selectList="normList">
		</w-picker>
	</view>
</template>

<script>
	import wPicker from "@/colorui/components/w-picker/w-picker.vue";
	import { addOrder,getUserListByRoleId,getOrder} from '@/api/modules/order.js';
	import { listNorm} from '@/api/modules/norm.js';
	import { listCoupon} from '@/api/modules/coupon.js';
	import wePay from '@/static/js/mPay.js';
	import md5 from '@/static/js/md5.js';
	
	
	import vPinyin from '@/static/js/py.js';
	export default {
		name: "add",
		components:{
		        wPicker
		},
		data() {
			return {
				member:uni.getStorageSync('member'),
				simpleTypeId:"",
				simpleTypeName:"",
				simpleTypeList:[],
				simpleIndex:0,
				acceptUserList:[],
				normList:[],
				couponList:[],
				totalAmount:0,
				deductAmount:0,
				actualAmount:0,
				order:{
					orderId:"",
					orderNumber:"",
					submitUserId:uni.getStorageSync('member')?uni.getStorageSync('member').userId:"",
					submitName:uni.getStorageSync('member')?uni.getStorageSync('member').nickName:"",
					submitPhone:uni.getStorageSync('member')?uni.getStorageSync('member').phonenumber:"",
					acceptRegName:"江苏省南通市如东县",
					submitDate:"",
					acceptUserId:"",
					acceptUserName:"",
					totalAmount:0,
					deductAmount:0,
					actualAmount:0,
					orderDetail:[],
					delFlag:0  //0 默认草稿 3-未受理 5-已受理
				}
			};
		},
		onLoad(options) {
			if(options.simpleTypeId){
				this.simpleTypeId=options.simpleTypeId
				this.simpleTypeName=options.simpleTypeName
			}
			if(options.orderId){
				this.order.orderId=options.orderId
			}
		},
		onReady() {
			this.getSimpleNormList()
			this.getCouponList()
		},
		onShow() {
				let date =new Date()
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				if(month<10){
					month="0"+month
				}
				let day=date.getDate()
				if(day<10){
					day="0"+day
				}
				this.order.submitDate=year+"-"+month+"-"+day
				if(this.order.orderId!=""){	
					this.getOrderDetail()
				}else{
					//如果是修改不用新增一个空的
					this.simplePush()
				}
				
				this.getUserList()
			try{
				this.simpleTypeList=uni.getStorageSync("simpleTypeList")
				if(this.simpleTypeId&&this.simpleTypeId!=""){
					this.order.orderDetail[0].simpleTypeId=this.simpleTypeId
					this.order.orderDetail[0].simpleTypeName=this.simpleTypeName
					
				}
			}catch(e){
				//TODO handle the exception
			}
		},
		watch:{
			totalAmount(val){
				let self=this
				this.couponList.forEach((item,index)=>{
					if(self.totalAmount>=item.totalAmount){
						self.deductAmount=item.coupon
					}
				})
				this.actualAmount=this.totalAmount-this.deductAmount
			}
		},
		methods: {
			getCouponList(){
				listCoupon({}).then(res=>{
					if(res.data.code==200){
						this.couponList=res.data.rows
					}
				})
			},
			getSimpleNormList(){
				let self=this
				listNorm({}).then(res=>{
					if(res.data.code==200){
						let list=res.data.rows
						for(let index in list){
							let norm=list[index]
							self.normList.push({label:norm.simpleNormName,value:norm.unitPrice})
							if(index==0){
								this.order.orderDetail[index].norm=norm.simpleNormName
								this.order.orderDetail[index].amount=norm.unitPrice
								self.totalAmount=norm.unitPrice
							}
						}
					}
				})
			},
			getOrderDetail(){
				let self=this
				getOrder(this.order.orderId).then(res=>{
					if(res.data.code==200){
						console.log(res.data.data)
						self.order=res.data.data
					}
				})
			},
			addOrder(state){
				let self=this
				if(!this.order.acceptUserId){
					uni.showToast({
						title:"填写接收人",
						duration:2000,
						success() {
						}
					})
					return;
				}
				if(!this.order.orderDetail[0].simpleTypeId){
					uni.showToast({
						title:"选择样品",
						duration:2000,
						success() {
						}
					})
					return;
				}
				let originalCodeFlag=false;
				let details=this.order.orderDetail
				for (let index in details) {
					let detail=details[index]
					if(detail.originalCode==''){
						originalCodeFlag=true;
						break;
					}
				}
				if(originalCodeFlag){
					uni.showToast({
						title:"请输入原始编码",
						duration:2000,
						success() {
						}
					})
					return;
				}
				
				self.order.delFlag=state
				self.order.totalAmount=this.totalAmount
				self.order.deductAmount=this.deductAmount
				self.order.actualAmount=this.actualAmount
				if(state==3){
					uni.showModal({
					    title: '提示',
					    content: '下单后将不可修改，确认下单？',
					    success: function (res) {
					        if (res.confirm) {
								self.addOrderReqeust()
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					        }
					    }
					});
				}else{
					self.addOrderReqeust()
				}
				
			},
			addOrderReqeust(){
				addOrder(this.order).then(res=>{
					if(res.data.code==200){
						if(this.order.delFlag>0){
							let data=res.data.data
							
							let timestamp = String(Date.now());
							let temp="appId="+data.appid+"&nonceStr="+data.nonceStr+"&package=prepay_id="+
								data.prepayId+"&signType=MD5&timeStamp="+timestamp+
								"&key=H57un019Tarray6354072gfw257jsqw9"
							let paySign=md5(temp)
							let packages="prepay_id="+data.prepayId
							wePay("wxpay", timestamp, data.nonceStr, packages, "MD5", paySign,res=>{
								uni.showToast({
									title:"下单并支付成功",
									duration:2000,
									success() {
										setTimeout(function(){
											uni.navigateBack({
												delta: 1
											});
										},2000)
									}
								})
							},fail=>{
								uni.showToast({
									title:"支付失败",
									duration:2000,
									success() {
                                        setTimeout(function(){
                                            uni.navigateBack({
                                                delta: 1
                                            });
                                        },2000)
									}
								})
							})
						}
						
					}else{
                        uni.showToast({
                            title:res.data.msg,
                            duration:2000,
                            success() {
                            }
                        })
					}
				})
			},
			getUserList(){
				let self=this
				getUserListByRoleId().then(res=>{
					if(res.data.code==200){
						let userList=res.data.data
						for (let index in userList) {
							self.acceptUserList.push({
								label:userList[index].nickName,
								value:userList[index].userId
							});
						}
					}
				})
			}
			,
			showRegionPicker(){
				let self=this
				this.$refs.region.show()
			},
			//省市区选择
			regionChoose(e){
				this.order.acceptRegName=e.checkArr[0]+''+e.checkArr[1]+''+e.checkArr[2];
				this.$refs.region.hide()
			},
			showDatePicker(){
				this.$refs.date.show()
			},
			//日期选择
			dateChoose(e){
				this.order.submitDate=e.result
				this.$refs.date.hide()
			},
			//选择样品种类
			simpleTypeShow(index){
				this.simpleIndex=index
				this.$refs.simpleType.show()
			},
			simpleTypeChoose(selector){
				this.order.orderDetail[this.simpleIndex].simpleTypeId=selector.checkArr.value
				this.order.orderDetail[this.simpleIndex].simpleTypeName=selector.checkArr.label
			},
			//选择接收人
			acceptUserShow(){
				this.$refs.acceptUser.show()
			},
			acceptUserChoose(selector){
				this.order.acceptUserId=selector.checkArr.value
				this.order.acceptUserName=selector.checkArr.label
			},
			//选择检测指标
			normShow(index){
				this.simpleIndex=index
				this.$refs.norm.show()
			},
			normChoose(selector){
				this.order.orderDetail[this.simpleIndex].norm=selector.checkArr.label
				this.order.orderDetail[this.simpleIndex].amount=selector.checkArr.value
				let totalAmount=0.00
                for (let index in this.order.orderDetail) {
                    totalAmount=totalAmount+this.order.orderDetail[index].amount
                }
                this.totalAmount=totalAmount
			},
			simplePush(){
				let normName=""
				let amount=""
				if(this.normList.length>0){
					normName=this.normList[0].label
					amount=this.normList[0].value
					this.totalAmount=this.totalAmount+amount
				}

				this.order.orderDetail.push({simpleTypeId:this.simpleTypeId,simpleTypeName:this.simpleTypeName,norm:normName,amount:amount,orderNumber:"",originalCode:""})
			},
			simpleRemove(){
				let orderDetail=this.order.orderDetail[this.order.orderDetail.length-1]
				this.deductAmount=0
				this.totalAmount=this.totalAmount-orderDetail.amount
				this.order.orderDetail.pop()
			},
			updateSimplePush(){
			},
			inputPY (label) {
			   let pingying= vPinyin.chineseToPinYin(label);
			   let SX = '';
			   for (var i = 0; i < pingying.length; i++) {
			      var c = pingying.charAt(i);
			      if (/^[A-Z]+$/.test(c)) {
			           SX += c;
			      }
			   }
			   return SX;
			},
			randomNumber() {
				let now = new Date();
				let year = now.getFullYear();       //年
				let month = now.getMonth() + 1;     //月
				let day = now.getDate();            //日
				let hh = now.getHours();            //时
				let mm = now.getMinutes();          //分
				let ss = now.getSeconds();           //秒
				let clock = year + "";
				if(month < 10)
					clock += "0";
		 
				clock += month + "";
		 
				if(day < 10)
					clock += "0";
		 
				clock += day + "";
				clock+= (Math.round(Math.random() * 23 + 100)).toString()
				return(clock);
			}
		},
	}
</script>

<style>
	
	.add-main{
	}
	.coverImage{
		height: 350upx;
	}
	.cu-card>.cu-item {
	    border-radius:0;
	    margin: 0;
	}
	.tab{
		margin-top: 80upx;
	}
	.save-btn{
		bottom:0;
	}
	.add-scroll{
		margin-bottom: 130upx;
	}
	.basis-regin{
		flex-basis: 72%
	}
</style>
